package com.xhq.wms.controller;
import com.xhq.webmvc.annotation.RequestBean;
import com.xhq.webmvc.annotation.RequestMapping;
import com.xhq.webmvc.annotation.ResponseJson;
import com.xhq.webmvc.model.JSONResponse;
import com.xhq.wms.entity.system.User;
import com.xhq.wms.service.system.impl.LoginServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_DATE;
import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet
@RequestMapping
public class LoginController {
    private LoginServiceImpl loginService = new LoginServiceImpl();

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    /**
     * @return
     */
    @RequestMapping("/login/verify")
    @ResponseJson
    public JSONResponse verify(  String userName,  String password,  String captcha, HttpServletRequest request) throws SQLException {
        int code = JSONResponse.CODE_SUCCESS;
        String msg = "登陆成功";
        HttpSession session = request.getSession();
        String sessionCode = (String)session.getAttribute(KAPTCHA_SESSION_KEY);
        Date date = (Date)session.getAttribute(KAPTCHA_SESSION_DATE);
        if(null == sessionCode || null == captcha || !sessionCode.equals  (captcha) || ((System.currentTimeMillis() - date.getTime()) /1000/ 60 > 15) ) {
            code = JSONResponse.CODE_FAIL;
            msg = "验证码错误或失效";
        }else {
            User user = loginService.login(userName, password);
            if(null != user) {
                session.setAttribute("user", user);    //登陆成功则将用户信息存入session
            }else {
                code = JSONResponse.CODE_FAIL;
                msg = "用户名或密码错误";
            }
        }
        session.removeAttribute(KAPTCHA_SESSION_KEY);
        session.removeAttribute(KAPTCHA_SESSION_DATE);
        return new JSONResponse(code, msg);
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return "redirect:/login";
    }
}
